package com.itcast.tanhuaserver.interceptor;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.itcast.tanhuaserver.utils.Cache;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @PachageName: com.itcast.tanhuaserver.interceptor
 * @ClassName:
 * @Description: TODO
 * @Author: Hushi
 * @DateTime: 2021/2/1614:37
 * @Version 1.0
 */
@ControllerAdvice
public class RedisCacheInterceptor implements HandlerInterceptor {
    @Value("${tanhua.cache.enable}")
    private Boolean enable;

    private static final ObjectMapper MAPPER = new ObjectMapper();

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //缓存的全局开关
        if (!enable){
            return true;
        }

        //判断此handle是否是HandlerMethod
        if (!(handler instanceof HandlerMethod)){
            return true;
        }

        //是否是get请求
        if (!((HandlerMethod) handler).hasMethodAnnotation(GetMapping.class)){
            return true;
        }

        //是否添加了Cache注解
        if (!((HandlerMethod) handler).hasMethodAnnotation(Cache.class)){
            return true;
        }

        //缓存命中
        String rediskey = createRedisKey(request);
        String value = this.redisTemplate.opsForValue().get(rediskey);
        if (StringUtils.isEmpty(value)){
            //缓存未命中
            return true;
        }

        //响应数据
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        response.getWriter().write(value);

        return false;
    }

    /**
     * 生成redis中的key，规则：SERVER_CACHE_DATA_MD5(url + param + token)
     *
     * @param request
     * @return
     */
    public static String createRedisKey(HttpServletRequest request) {
        String url = request.getRequestURI();
        String param = null;
        try {
            param = MAPPER.writeValueAsString(request.getParameterMap());
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        String token = request.getHeader("Authorization");
        String data = url + "_" + param + "_" + token;

        return "SERVER_CACHE_DATA_" + DigestUtils.md5Hex(data);
    }
}
